package com.ygj.employeeReport.service.base.impl;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;

import com.base.common.ConfigConstants;
import com.base.common.enums.TicketCategories;
import com.base.common.json.JsonUtil;
import com.base.common.persistent.dao.EmployeeCompoundsMapper;
import com.base.common.persistent.dao.TicketMapper;
import com.base.common.persistent.model.Employee;
import com.base.common.persistent.model.Ticket;
import com.base.common.utils.EasyUtil;
import com.cjy.common.bean.Files;
import com.ygj.employeeReport.service.base.TicketBaseService;

/**
 * 工单实现基类
 * 
 * @author Kevin Colin
 *
 */
public class TicketBaseServiceImpl implements TicketBaseService {

	static Logger logger = Logger.getLogger(Class.class);

	@Resource
	private TicketMapper ticketMapper;

	@Resource
	private EmployeeCompoundsMapper employeeCompoundsMapper;

	@Resource
	private EasyUtil easyUtil;

	@Override
	public int getTicketsPagessByUserIdAndCategories(Ticket ticket) {
		int totalTicketsCounts = ticketMapper
				.queryTotalByCategoriesAndUserId(ticket);
		int totalPages = (totalTicketsCounts % 15 == 0) ? (totalTicketsCounts / 15)
				: (totalTicketsCounts / 15 + 1);
		return totalPages;
	}

	@Override
	public int getStartNum(int page) {
		return (page - 1)
				* Integer.valueOf(ConfigConstants.INFOS_LIST_NUM.trim());

	}

	@Override
	public int getEndNum(int page) {
		return page * Integer.valueOf(ConfigConstants.INFOS_LIST_NUM.trim());
	}

	@Override
	@Transactional
	public String subTickets(Ticket ticket, boolean disflag, Files files, String basePath,
							 int bid) {
		// 设置接单时间
		ticket.setGetTime(easyUtil.getDateStrByGeneral(new Date()));

		// 设置状态为派单
		ticket.setStatus(ticket.getStatus());

		// 设置工单类别
		ticket.setCategories(ticket.getCategories());

		// 设置员工小区中间表id
		int employeeCompoundsId = employeeCompoundsMapper
				.queryEmployeeCompoundsIdByEmployeeIdAndCompoundsId(ticket
						.getEmployee().getId(), ticket.getCompounds().getId());
		if (employeeCompoundsId == 0) {
			return null;
		}

		ticket.setEmployeeCompoundsId(employeeCompoundsId);
		// 设置工单号，查询最新工单号，并在基础上加1
		List<Ticket> tickets = new ArrayList<Ticket>();
		Map<String, Object> categories = getTicketCategories(ticket
				.getCategories());
		String code = getComlaintCode(tickets, categories.get("name")
				.toString(),
				Integer.valueOf(categories.get("value").toString()));
		ticket.setCode(code);

		// 图片相对保存地址
		String sysImagesFile = "/resources/images/tickets" + "/" + code;

		// 保存图片
		String[] fileNames = files.getFileFileName();
		String picUrls = "";
		try {
			if (bid == 2) {
				picUrls = easyUtil.downloadFile(ticket.getPicUrls(), basePath,
						sysImagesFile, picUrls);
			} else {
				if (fileNames != null && fileNames.length != 0) {
					picUrls = easyUtil.savePictures(files.getFile(), basePath,
							sysImagesFile, fileNames, picUrls);
				}
			}
			ticket.setPicUrls(picUrls);
		} catch (IOException e) {
			return null;
		}
		if (ticketMapper.addTicket(ticket) > 0) {
			return code;
		}
		return null;
	}

	/**
	 * 获取工单类别信息
	 * 
	 * @param category
	 *            工单类别
	 * @return
	 */
	private Map<String, Object> getTicketCategories(int category) {
		Map<String, Object> categories = new HashMap<String, Object>();
		switch (category) {
		case 0:
			categories.put("name", TicketCategories.TEMPORARY.getName());
			categories.put("value", TicketCategories.TEMPORARY.getValue());
			break;
		case 1:
			categories.put("name", TicketCategories.REPAIR.getName());
			categories.put("value", TicketCategories.REPAIR.getValue());
			break;
		case 2:
			categories.put("name", TicketCategories.COMPLAINT.getName());
			categories.put("value", TicketCategories.COMPLAINT.getValue());
			break;
		case 3:
			categories.put("name", TicketCategories.ASSIGNMENT.getName());
			categories.put("value", TicketCategories.ASSIGNMENT.getValue());
			break;
		case 4:
			categories.put("name", TicketCategories.EMPLOYEECOMLAINT.getName());
			categories.put("value",
					TicketCategories.EMPLOYEECOMLAINT.getValue());
			break;
		case 5:
			categories.put("name", TicketCategories.PHENOMENON.getName());
			categories.put("value", TicketCategories.PHENOMENON.getValue());
			break;
		}
		return categories;
	}

	/**
	 * 生成投诉工单工单号
	 * 
	 * @param tickets
	 * @return
	 */
	private String getComlaintCode(List<Ticket> tickets, String prefixCode,
			int categories) {
		try {
			tickets = ticketMapper.queryLastCodeByCategories(categories);
		} catch (Exception e) {
			logger.info(e.fillInStackTrace());
			return null;
		}
		String code = "";
		DecimalFormat df = new DecimalFormat(ConfigConstants.TICKET_CODE_NUMS);
		if (tickets.size() != 0) {
			String lastedCode = tickets.get(0).getCode();
			System.out.println("***********************************");
			System.out.println(lastedCode);
			code = df.format(Integer.parseInt(lastedCode.substring(1).trim()) + 1);
			System.out.println(code);
		} else {
			code = df.format(1);
		}
		code = prefixCode + code;
		return code;
	}

	/**
	 * 根据工单类型和员工id获取工单总条数
	 * 
	 * @param employeeId
	 * @param ticketCategories
	 * @return
	 */
	@Override
	public int getTicketCounts(int employeeId, int ticketCategories) {
		Ticket ticket = new Ticket();
		ticket.setEmployee(new Employee().setId(employeeId));
		ticket.setCategories(ticketCategories);
		logger.info("进入ticketMapper --> queryTotalByCategoriesAndEmployeeId\n参数：\n"
				+ JsonUtil.dto2String(ticket));
		return ticketMapper.queryTotalByCategoriesAndEmployeeId(ticket);
	}
}
